<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table{
            width: 100%;
            border: 1px solid #ccc;
            border-collapse: collapse;
            border-spacing: 0px;
        }
        table td{
            border: 1px solid #ccc;
            height: 30px;
        }
    </style>
</head>
<body>
    <div class="box">
        <h1>使用创建DOM节点动态生成表格</h1>
        <label for="">行：</label>
        <input type="text" name="" id="row">
        <label for="">列：</label>
        <input type="text" name="" id="col">
        <input type="button" name="" id="btn" value="生成">
        <div id="output">
            <!-- <table>
                <tbody>
                    <tr>
                        <td>

                        </td>
                    </tr>
                </tbody>
            </table> -->
        </div>
    </div>
</body>
<script>
    var btn = document.getElementById('btn');
    var col = document.getElementById('col');
    var row = document.getElementById('row');
    var output = document.getElementById('output');

    var btn1 = document.getElementsByClassName('btn1');
    var btn2 = document.getElementsByClassName('btn2');
    
    btn.onclick = function(){
        var Row = row.value;        //  获取行数信息
        var Col = col.value;        //  获取列数信息

        var table = document.createElement('table');        //创建table标签
        var tbody = document.createElement('tbody');        //创建tbody标签

        table.appendChild(tbody);       //把tbody放在table中

        for(var i=0;i<Row;i++){
            var tr = document.createElement('tr');
            if(i % 2 == 0){
                tr.style.background = '#ccc'
            }
            for(var j=0;j<Col;j++){
                var td = document.createElement('td');
                if(j === 0){
                    td.innerHTML = '' + (i+1);
                }else{
                    td.innerHTML = '单元格' + i + '行' + j + '列';
                }
                tr.appendChild(td);  
                if(j == Col-1){
                    td.innerHTML = '<button class="btn1">复制</button>'+'<button class="btn2">删除</button>'
                }
            }
            tbody.appendChild(tr)
        }
        output.appendChild(table);
        for(let k=0;k<btn2.length;k++){
            btn2[k].onclick = function(){
                this.parentElement.parentElement.remove();
            }
        }
        for(let v=0;v<btn1.length;v++){
            btn1[v].onclick = function(){
                var n = this.parentElement.parentElement.cloneNode(true);
                tbody.appendChild(n)
            }
        }
    }
</script>
</html>